package com.xf.balance;

import java.util.Arrays;
import java.util.stream.Collectors;

public class WeightAlgorithm {

    class WA{
        PowerWeight pw;
        int current =0;
        WA(PowerWeight pw){
            this.pw = pw;
        }
    }

    final WA[] cacheWeights ;

    public WeightAlgorithm(PowerWeight[] powerWeights) {
        this.cacheWeights = Arrays.stream(powerWeights)
                .map(WA::new).collect(Collectors.toList()).toArray(new WA[0]);
    }

    public String next(){
        int total =0 ;
        WA shed = cacheWeights[0];
        for (WA item : cacheWeights) {
            int weight = item.pw.weight;
            total += weight;

            item.current += weight;
            if (item.current > shed.current){
                shed = item;
            }
        }
        shed.current -= total;
        printCache();
        return shed.pw.resource;

    }

    private void printCache() {
        System.out.println();
        for (WA cacheWeight : cacheWeights) {
            System.out.print(cacheWeight.pw.weight + "," + cacheWeight.current + "|");
        }
        System.out.println();
    }

}
